<template>
  <div>
    <!-- 添加或修改博客管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      fullscreen
      custom-class="inner-dialog"
      :destroy-on-close="true"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row class="blog-base-info-container">
          <el-col :span="6">
            <el-form-item label="封面图片">
              <image-upload
                :visible.sync="dialogVisible"
                @setImageUrl="setImageUrl"
                :limit="1"
                :file-size="10"
                :file-path="upload.path"
                :value="form.blogImage"
              />
            </el-form-item>
          </el-col>
          <el-col :span="18" class="row-content">
            <el-col :span="16">
              <el-form-item label="文章标题" prop="blogTitle">
                <el-input v-model="form.blogTitle" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文章分类" prop="blogType">
                <treeselect
                  v-model="form.blogType"
                  :options="typeOptions"
                  :normalizer="normalizer"
                  :show-count="true"
                  placeholder="选择文章分类"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="标签">
                <div class="tag-form-item">
                  <el-select v-model="tagValues" multiple :multiple-limit="5" clearable filterable placeholder="请选择">
                    <el-option
                      v-for="item in tagList"
                      :key="item.id"
                      :label="item.tagName"
                      :value="item.id"
                    />
                  </el-select>
                  <span style="padding-left:2%;">
                    <el-button icon="el-icon-plus" circle @click="openAddTagDialog"/>
                  </span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="推荐等级" prop="blogRecommend">
                <el-select v-model="form.blogRecommend" placeholder="请选择推荐等级" clearable>
                  <el-option
                    v-for="dict in dict.type.bl_recommend_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文章来源" prop="original">
                <el-radio-group v-model="form.original">
                  <el-radio
                    v-for="dict in dict.type.bl_blog_original"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="文章出处" prop="blogSource" :rules="form.original === '1' ? [] : [{ required: true, message: '文章出处不能为空', trigger: 'blur' }]">
                <el-input v-model="form.blogSource" placeholder="文章来源为转载时，请注明文章出处" :disabled="form.original === '1'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文章状态" prop="status">
                <el-radio-group v-model="form.status" @input="handleStatusChange">
                  <el-radio
                    v-for="dict in dict.type.bl_blog_status"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="评论状态" prop="commentOpen">
                <el-radio-group v-model="form.commentOpen">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <!--            <el-col :span="8">
                          <el-form-item label="复核状态">
                            <el-radio-group v-model="form.approvalStatus" :disabled="true">
                              <el-radio
                                v-for="dict in dict.type.sys_approval_status"
                                :key="dict.value"
                                :label="dict.value"
                              >{{dict.label}}</el-radio>
                            </el-radio-group>
                          </el-form-item>
                        </el-col>-->

          </el-col>
          <el-col :span="24">
            <el-form-item label="文章简介" prop="blogRemark">
              <el-input v-model="form.blogRemark" type="textarea" :rows="2" placeholder="请输入简介" />
            </el-form-item>
            <el-divider content-position="left">文章内容</el-divider>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <tinymce-editor v-model="form.blogContent" v-if="dialogVisible"/>
          </el-col>
        </el-row>

      </el-form>
      <!-- 添加标签弹窗 -->
      <el-dialog
        title="添加标签"
        :visible.sync="addTagDialog"
        :destroy-on-close="true"
        :modal-append-to-body="true"
        append-to-body
        width="500px"
        v-drag-zoom
      >
        <el-form ref="tagForm" :model="newTag" label-width="80px" >
          <el-row>
            <el-col :span="24">
              <el-form-item label="标签名">
                <el-input v-model="newTag.tagName" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="newTag.remark" type="textarea" rows="3" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="onAddTagSubmit">提交</el-button>
          <el-button size="mini" @click="closeAddTagDialog">取消</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import {getToken} from "@/utils/auth";
import {addTag, queryAllTag, queryByTagName} from "@/api/blog/tag";
import {addBlog, updateBlog} from "@/api/blog/blog";
import {listAllType} from "@/api/blog/type";

export default {
  name: "insertOrUpdateDialog",
  components: {
    Treeselect
  },
  dicts: ['sys_normal_disable', 'bl_blog_status', 'sys_approval_status',
    'bl_blog_original', 'bl_recommend_level', 'bl_yes_no'],
  props: {
    // 文章详情
    blogInfo: {
      type: Object,
      default: () => {},
    },
    title: {
      type: String,
      default: "新增或修改文章",
    }
  },
  data() {
    return {
      // 是否显示弹出层
      dialogVisible: true,
      // 禁用复核选择
      disableApprovalStatus: false,
      // 控制添加标签弹窗显示
      addTagDialog: false,
      // 选中的标签
      tagValues: [],
      // 标签列表
      tagList: [],
      // 分类树选项
      typeOptions: [],
      // 标签
      newTag: {
        id: null,
        tagName: '',
        remark: ''
      },
      // 上传文件路径
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的文件夹
        path: '/blog/blog-cover',
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/file/upload"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        blogTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        blogContent: [
          { required: true, message: "帖子内容不能为空", trigger: "blur" }
        ],
        blogType: [
          { required: true, message: "博客分类不能为空", trigger: "change" }
        ],
        blogRecommend: [
          { required: true, message: "推荐等级不能为空", trigger: "blur" }
        ],
        commentOpen: [
          { required: true, message: "评论状态不能为空", trigger: "change" }
        ],
        original: [
          { required: true, message: "是否原创不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "文章状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getTagList();
    this.getTypeList();
    this.form = JSON.parse(JSON.stringify(this.blogInfo));
    if (this.form.tagList != null) {
      this.form.tagList.forEach(e => {
        this.tagValues.push(e.id)
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      const scrollEl = document.getElementsByClassName('el-dialog__body');
      if (scrollEl.length > 0) {
        const el = scrollEl[0];
        el.scrollTop = 0;
        document.addEventListener("scroll", this.handleScroll, true);
      }
    })
  },
  /** 销毁事件监听 */
  beforeDestroy() {
    document.removeEventListener("scroll", this.handleScroll, true);
  },
  methods: {
    /** 获取标签列表 */
    getTagList() {
      queryAllTag().then(res => {
        this.tagList = res.data
      })
    },
    /** 获取文章分类列表 */
    getTypeList() {
      listAllType().then(res => {
        const type = this.handleTree(res.data, "typeCode", "typeCodeP")
        type.forEach( e => {
          this.typeOptions.push(e)
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 置空tagList
          this.form.tagList = []
          this.tagValues.forEach(e => {
            const temp = {id: e, tagName: '', tagBlogCount: 0, createdTime: '', updateTime: ''};
            this.form.tagList.push(temp)
          })
          if (this.form.id != null) {
            updateBlog(this.form).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.$emit('closeDialog');
              this.$emit('getList');
            });
          } else {
            addBlog(this.form).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.$emit('closeDialog');
              this.$emit('getList');
            });
          }
        }
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.typeCode,
        label: node.typeName,
        children: node.children
      };
    },
    /** 打开添加弹窗 */
    openAddTagDialog() {
      if (this.tagValues.length < 5) {
        this.addTagDialog = true
      } else {
        this.$message.error('最多选择五个标签，请删除部分标签后操作')
      }
    },
    /** 回写图片地址 */
    setImageUrl(url) {
      this.form.blogImage = url;
    },
    /** 添加标签提交 */
    onAddTagSubmit() {
      addTag(this.newTag).then((res) => {
        this.$message.success(res.msg)
        this.getTagList()
        queryByTagName(this.newTag.tagName).then(res => {
          this.tagValues.push(res.data.id)
          this.closeAddTagDialog()
        })
      })
    },
    /** 文章状态变更 */
    handleStatusChange(val) {
      if (val==='0') {
        this.$set(this.form, 'approvalStatus', '3');
        this.disableApprovalStatus = true;
      } else {
        this.disableApprovalStatus = false;
        this.$set(this.form, 'approvalStatus', '2');
      }
    },
    /** 取消按钮 */
    cancel() {
      this.$emit('closeDialog')
    },
    /** 关闭添加标签弹窗 */
    closeAddTagDialog() {
      this.addTagDialog = false
    },
    /** 编写滚动条事件 */
    handleScroll() {
      // 获取滚动条元素对象
      const scrollEl = document.getElementsByClassName('el-dialog__body');
      if (scrollEl.length > 0) {
        const el = scrollEl[0];
        if (el !== null) {
          // 获取需要固定的元素对象
          const rightElArr = document.getElementsByClassName('tox-editor-header');
          if (rightElArr.length > 0) {
            let rightEl = rightElArr[0];
            const baseInfoEl = document.querySelector(".blog-base-info-container");
            let btnUploadEl = document.querySelector(".editor-custom-btn-container");
            const topHeight = (baseInfoEl?.clientHeight || 0) + 23;
            // 判断滚动条的高度（大于380，给固定元素添加 class）
            if (el.scrollTop > topHeight) {
              rightEl.classList.add('tox-editor-header-fixed');
              if (btnUploadEl) {
                btnUploadEl.classList.add('editor-custom-btn-container-fixed');
              }
            } else {
              rightEl.classList.remove('tox-editor-header-fixed');
              if (btnUploadEl) {
                btnUploadEl.classList.remove('editor-custom-btn-container-fixed');
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .inner-dialog {
  .el-upload--picture-card,.el-upload-list__item {
    width: 230px !important;
    height: 138px !important;
  }
}

.tag-form-item{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

</style>
